//
//  CPCellModal.m
//  News
//
//  Created by chen on 15/3/24.
//  Copyright (c) 2015年 chen. All rights reserved.
//

#import "CPCellModal.h"
#import "CPDataTool.h"

static NSString *document ;

@interface CPCellModal()

@end
@implementation CPCellModal

+ (void)setDocumentWithName:(NSString *)name{
    
    NSString *path =   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    document =  [path stringByAppendingPathComponent:name];
   
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:document]){
        
        return;
    }
                        
    NSString *pathPlist =   [[NSBundle mainBundle] pathForResource:name ofType:nil];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:pathPlist];
    
    [array writeToFile:document atomically:YES];

}

// 从CPCellModal 中去加载
+ (NSArray *)CellModals {
    
    [self setDocumentWithName:@"HomeCellModal.plist"];
    return  [self arrayForCellModalWithFileName:document];

}

+ (NSArray *)CellTotalModals {
    
   NSString *path = [[NSBundle mainBundle] pathForResource:@"HomeCellTotalModal.plist" ofType:nil];
    
    return  [self arrayForCellModalWithFileName:path];
    
}

+ (NSArray *)arrayForCellModalWithFileName:(NSString *)path{
    
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
    
    for (NSDictionary *dic  in array) {
        CPCellModal *modal = [[CPCellModal alloc] init];
        [modal setValue:dic[@"title"] forKey:@"title"];
        [modal setValue:dic[@"URLString"] forKey:@"URLString"];
        [arrayM addObject:modal];
    }
    return arrayM;

}

- (void)writeToPlist{
        
        NSMutableArray *arrayM = [NSMutableArray arrayWithContentsOfFile:document];
        
        NSDictionary *dic = @{@"title":self.title,
                              @"URLString":self.URLString};
        NSUInteger index = arrayM.count - 1;
        
        [arrayM insertObject:dic atIndex:index];
    
        [arrayM writeToFile:document atomically:YES];
    
}

@end
